package com.jiangyg.devtools.ui.table.cell;

import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.jiangyg.devtools.ui.AbstractDialogWrapper;
import com.jiangyg.devtools.ui.EditorTextAreaBuilder;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.EventObject;

/**
 * 类描述：编辑器文本域的单元格编辑器
 *
 * @author jiangyg
 * @version 1.0
 * @date 2023年08月29日
 */
public class EditorTextFieldCellEditor extends AbstractTableCellEditor {

    private final JBLabel component = new JBLabel();

    public EditorTextFieldCellEditor(Project project) {
        super(project);

        component.setForeground(JBColor.getHSBColor(108, 66, 66));
        UIUtil.addInsets(component, JBUI.insets(0, 10));
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
                                                 Object value,
                                                 boolean isSelected,
                                                 int rowIndex, int columnIndex) {
        final String string = String.valueOf(value);

        component.setText(string);
        component.setToolTipText(string);

        return component;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        new EditorTextAreaDialog(this).show();
        return super.shouldSelectCell(anEvent);
    }

    public void setText(String text) {
        this.component.setToolTipText(text);
    }

    public String getText() {
        return component.getToolTipText();
    }

    @Override
    public Object getCellEditorValue() {
        return component.getToolTipText();
    }

    private static class EditorTextAreaDialog extends AbstractDialogWrapper {

        private EditorTextField textField;

        private final EditorTextFieldCellEditor tableCellEditor;

        private EditorTextAreaDialog(EditorTextFieldCellEditor tableCellEditor) {
            super(tableCellEditor.getProject());

            this.tableCellEditor = tableCellEditor;

            this.setOKButtonText("确定");
            this.setCancelButtonText("取消");
            this.setSizeByRatio(0.5, 0.8);

            init();
        }

        @Override
        protected @Nullable JComponent createCenterPanel() {
            this.textField = EditorTextAreaBuilder.instance()
                    .project(project).defaultFeatures().build(PlainTextLanguage.INSTANCE);
            this.textField.setText(tableCellEditor.getText());
            return textField;
        }

        @Override
        protected void doOKAction() {
            tableCellEditor.setText(textField.getText());
            tableCellEditor.stopCellEditing();
            super.doOKAction();
        }

    }

}
